import fileinput

class OneMarkov(object):
    def __init__(self):
        self.markov_dic={}
        self.average=0
        self.count=0
        self.no_request=0
        self.no_of_request=0
        self.n=0

    def initial_train(self):

        for line in fileinput.input(['D:\\train_d.csv']):
                try:
                        self.markov_dic=self.train(line,self.markov_dic)
                except:
                    continue
        return self.markov_dic
             
    def train(self,session,markov_dic): # this is a training method 
        total_frequency=0
        print "INSIDE TRAIN"
        session= session.strip().rstrip(',')
        session_elements=session.split(',') # to get the elements/domain number in a sessions
        length=len(session_elements)-1
        for i in range(0,length):
            j=i+1
            if markov_dic.has_key(session_elements[i]):
                value=markov_dic.get(session_elements[i])
                total_frequency=value[0]
                inner_dic=value[1]
                total_frequency=int(total_frequency)+1
                if inner_dic.has_key(session_elements[j]):
                    inner_dic[session_elements[j]]=int(inner_dic.get(session_elements[j]))+1
                else:
                    inner_dic[session_elements[j]]=1
                    markov_dic[session_elements[i]]=(total_frequency,inner_dic)
            else:
                total_frequency=1
                inner_dic={}
                inner_dic[session_elements[j]]=1
                markov_dic[session_elements[i]]=(total_frequency,inner_dic)
        return markov_dic
    
        
    
    def recommend(self,d1,dic1):
        recommendation_list =[]
        value=dic1.get(d1)
        if (value==None):
            return recommendation_list
        inner_dic= value[1]
        recommendation_list=sorted(inner_dic.iteritems(), key=lambda (k,v): (v,k))
        recommendation_list.reverse()
        len1=len(recommendation_list)
        resultlist=[]
        for u in range(0,len1):
            resultlist.append((recommendation_list[u])[0])
        return resultlist[0:20]
    
    
    def evaluate(self,recommendationlist,actual,c,accuracy):
        correct=0
        if actual in recommendationlist:
            correct=1
            accuracy = self.calculateAccuracy(1,accuracy,c)
            return (accuracy,c,correct)
        else:
            correct=0
            accuracy=self.calculateAccuracy(0,accuracy,c)
            return (accuracy,c,correct)
        
    def calculateAccuracy(self,correct,a,c):
        return ((int(c)-1)*float(a)+int(correct))/int(c)